/**
 * 渲染咨询行政区划
 */
function renderArea(region){
	$.ajax({
		url: ctx + "/custom-config/gdbsNav/getDetail",
		data: {regCode:region},
		type: "POST",
		dataType: 'json', //返回值类型 一般设置为json
		success: function(result) {
			if(result.statusCode == '200' && result.data){
				//var city = result.data.data.city;
				var cityStr = 
				 '[{"id":10200000005,"province":"广东省","city":"","county":"","town":"","ORGNAME":"珠海市","ORGSNAME":"珠海市","ORGAREACODE":"440400","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440400","SORT":3,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000007,"province":"广东省","city":"","county":"","town":"","ORGNAME":"佛山市","ORGSNAME":"佛山市","ORGAREACODE":"440600","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440600","SORT":5,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'	
				+'{"id":10200000015,"province":"广东省","city":"","county":"","town":"","ORGNAME":"河源市","ORGSNAME":"河源市","ORGAREACODE":"441600","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=441600","SORT":7,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000014,"province":"广东省","city":"","county":"","town":"","ORGNAME":"汕尾市","ORGSNAME":"汕尾市","ORGAREACODE":"441500","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=441500","SORT":10,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000019,"province":"广东省","city":"","county":"","town":"","ORGNAME":"中山市","ORGSNAME":"中山市","ORGAREACODE":"442000","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=442000","SORT":12,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000016,"province":"广东省","city":"","county":"","town":"","ORGNAME":"阳江市","ORGSNAME":"阳江市","ORGAREACODE":"441700","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=441700","SORT":14,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000009,"province":"广东省","city":"","county":"","town":"","ORGNAME":"湛江市","ORGSNAME":"湛江市","ORGAREACODE":"440800","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440800","SORT":15,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000010,"province":"广东省","city":"","county":"","town":"","ORGNAME":"茂名市","ORGSNAME":"茂名市","ORGAREACODE":"440900","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440900","SORT":16,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
				+'{"id":10200000006,"province":"广东省","city":"","county":"","town":"","ORGNAME":"汕头市","ORGSNAME":"汕头市","ORGAREACODE":"440500","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440500","SORT":4,"ORGNUMBER":"","credit":null,"responsibility_list":"1"}]'
				var city = JSON.parse(cityStr);
				var country = result.data.data.country;
				var template = "<option value='#value#'>#text#</option>"
				var city_html = "";
				var current;
				$(city).each(function(i,item){
					if(region == item.ORGAREACODE){
						current = item;
					}
					city_html += template.replace("#text#",item.ORGNAME).replace("#value#",item.ORGAREACODE);
				});
				city_html = "<option value='440000'>省级</option>"+city_html;
				$("#city").html(city_html);
				var country_html = "";
				if(country.length == 0){
					country_html += template.replace("#text#","暂无可选择区县").replace("#value#","0");
					$("#country").val("0");
				}else{
					$(country).each(function(i,item){
						if(region == item.ORGAREACODE){
							current = item;
						}
						country_html += template.replace("#text#",item.ORGNAME).replace("#value#",item.ORGAREACODE);
					});
					country_html = "<option value=''></option>"+country_html;
				}
				$("#country").html(country_html);
				
				if("440000" == region){
					$("#country").parent().hide();
					return ;
				}
				$("#country").parent().show();
				if("市分厅" == current.ORGTYPE){
					$("#city").val(current.ORGAREACODE);
				}
				if("区县分厅" == current.ORGTYPE){
					$("#city").val(current.ORGUPAREACODE);
					$("#country").val(current.ORGAREACODE);
				}
				
			}
			
		},
		error: function (data, status, e) {
			alert("区划加载对象失败");
		}
	});
}

/**
 * 渲染投诉行政区划
 */
function renderTsArea(region,flag){
	$.ajax({
		url: ctx + "/custom-config/gdbsNav/getDetail",
		data: {regCode:region},
		type: "POST",
		dataType: 'json', //返回值类型 一般设置为json
		success: function(result) {
			if(result.statusCode == '200' && result.data){
				//var city = result.data.data.city;
				var cityStr = 
					'[{"id":10200000005,"province":"广东省","city":"","county":"","town":"","ORGNAME":"珠海市","ORGSNAME":"珠海市","ORGAREACODE":"440400","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440400","SORT":3,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000007,"province":"广东省","city":"","county":"","town":"","ORGNAME":"佛山市","ORGSNAME":"佛山市","ORGAREACODE":"440600","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440600","SORT":5,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'	
					+'{"id":10200000015,"province":"广东省","city":"","county":"","town":"","ORGNAME":"河源市","ORGSNAME":"河源市","ORGAREACODE":"441600","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=441600","SORT":7,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000014,"province":"广东省","city":"","county":"","town":"","ORGNAME":"汕尾市","ORGSNAME":"汕尾市","ORGAREACODE":"441500","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=441500","SORT":10,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000019,"province":"广东省","city":"","county":"","town":"","ORGNAME":"中山市","ORGSNAME":"中山市","ORGAREACODE":"442000","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=442000","SORT":12,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000016,"province":"广东省","city":"","county":"","town":"","ORGNAME":"阳江市","ORGSNAME":"阳江市","ORGAREACODE":"441700","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=441700","SORT":14,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000009,"province":"广东省","city":"","county":"","town":"","ORGNAME":"湛江市","ORGSNAME":"湛江市","ORGAREACODE":"440800","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440800","SORT":15,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000010,"province":"广东省","city":"","county":"","town":"","ORGNAME":"茂名市","ORGSNAME":"茂名市","ORGAREACODE":"440900","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440900","SORT":16,"ORGNUMBER":"","credit":null,"responsibility_list":"1"},'
					+'{"id":10200000006,"province":"广东省","city":"","county":"","town":"","ORGNAME":"汕头市","ORGSNAME":"汕头市","ORGAREACODE":"440500","ORGUPAREACODE":"440000","ORGTYPE":"市分厅","DISPLAY":"1","SITES_URL":"http://mh.digitalgd.com.cn/portal/index?region=440500","SORT":4,"ORGNUMBER":"","credit":null,"responsibility_list":"1"}]'
					var city = JSON.parse(cityStr);
				var country = result.data.data.country;
				var template = "<option value='#value#'>#text#</option>"
					var city_html = "";
				var current;
				$(city).each(function(i,item){
					if(region == item.ORGAREACODE){
						current = item;
					}
					city_html += template.replace("#text#",item.ORGNAME).replace("#value#",item.ORGAREACODE);
				});
				city_html = "<option value='440000'>省级</option>"+city_html;
				$("#city").html(city_html);
				var country_html = "";
				if(country.length == 0){
					country_html += template.replace("#text#","暂无可选择区县").replace("#value#","0");
					$("#country").val("0");
				}else{
					$(country).each(function(i,item){
						if(region == item.ORGAREACODE){
							current = item;
						}
						country_html += template.replace("#text#",item.ORGNAME).replace("#value#",item.ORGAREACODE);
					});
					country_html = "<option value=''></option>"+country_html;
				}
				if(flag){
					$("#country").html(country_html);
				}
				if(current){
					$("input[name='xzqhmz']").val(current.ORGNAME);
					$("input[name='orgtype']").val(current.ORGTYPE);
					$("input[name='orgupareacode']").val(current.ORGUPAREACODE);
					$("input[name='orgupareaname']").val(current.city);
				}else{
					var id = $("#city  option:selected").val();
					var text = $("#city  option:selected").text();
					if(text == "省级" && id == "440000"){
						$("input[name='xzqhdm']").val(id);
						$("input[name='xzqhmz']").val("广东省");
						$("input[name='orgtype']").val("市分厅");
					}
				}				
				
				if("440000" == region){
					$("#country").parent().hide();
					return ;
				}
				$("#country").parent().show();
				if("市分厅" == current.ORGTYPE){
					$("#city").val(current.ORGAREACODE);
				}
				if("区县分厅" == current.ORGTYPE){
					$("#city").val(current.ORGUPAREACODE);
					$("#country").val(current.ORGAREACODE);
				}
				
			}
			
		},
		error: function (data, status, e) {
			alert("区划加载对象失败");
		}
	});
}

/**
 * 初始化select2（带分页）
 * @param selector	select的id
 * @param url	数据来源接口
 */
function initAjaxSelect2(selector, url, nullMsg,region) {
    $(selector).select2({
      ajax: {
        url: url,
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                keyword: params.term, // search term 请求参数 ， 请求框中输入的参数
                page: params.page,
                zzjgdm: $("#deptCode").val(),
                region:region
            };
        },
        processResults: function (result, params) {
            params.page = params.page || 1;
            var itemList = [];//当数据对象不是{id:0,text:'ANTS'}这种形式的时候，可以使用类似此方法创建新的数组对象
            var data = null;
            var totalCount = null;
            if(result.result){
            	data = result.result.data;
            	totalCount = result.result.totalCount;
            }
            if(result && !result.error) {
            	itemList = data;
            }
            return {
                results: itemList,
                pagination: {
                    more: (params.page * 10) < totalCount
                }
            };
        }
      },
      language: {
    	  loadingMore:function(){return "加载中…"},
    	  searching:function(){return "搜索中…"},
    	  noResults:function(){return nullMsg},
    	  errorLoading:function(){return nullMsg}
      }
    });
}

/**
 * 初始化select2（不带分页）
 * @param selector	select的id
 * @param url	数据来源接口
 */
function initAjaxSelect2WithNoPage(selector, url, nullMsg) {
    $(selector).select2({
      ajax: {
        url: url,
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                keyword: params.term, // search term 请求参数 ， 请求框中输入的参数
            };
        },
        processResults: function (result, params) {
            var itemList = [];//当数据对象不是{id:0,text:'ANTS'}这种形式的时候，可以使用类似此方法创建新的数组对象
            if(result && !result.error) {
            	itemList = result.result;
            }
            return {
                results: itemList,
            };
        }
      },
      language: {
    	  loadingMore:function(){return "加载中…"},
    	  searching: function(){return "搜索中…"},
    	  noResults: function(){return nullMsg},
    	  errorLoading: function(){return nullMsg}
      }
    });
}

/**
 * 文件后缀名判断
 * @param filename
 * @returns {Boolean} true-后缀名合法；false-后缀名不合法
 */
function checkFileExt(file)
{
	var filename = file.name;
	if(filename == undefined){
		filename = file;
	}
	//文件名为空，返回错误
	if(!filename) {
		return false;
	}
    var flag = false; //状态
    var arr = ["png","jpg","jpeg","pdf","doc","docx","xls","xlsx","txt","zip",
               "gif","wav","mp3","wma","aac","mp4","rmvb","rm","mkv","avi"];
    //取出上传文件的扩展名
    var index = filename.lastIndexOf(".");
    var ext = filename.substr(index+1);
    //循环比较
    for(var i=0;i<arr.length;i++)
    {
        if(ext == arr[i] || ext == arr[i].toUpperCase())
        {
            flag = true;  //一旦找到合适的，立即退出循环
            break;
        }
    }
    return flag;
}

function checkFile(file,form){
	if(!file) {
		return false;
	}
	if(form.find(".gd-upload-item").length > 0) {
		alert("最多只允许上传一个附件，请先删除原来的附件");
		return false;
	}
	if(file.size != undefined && file.size > 30*1024*1024) {
		alert("文件大小超过限制，请重新上传");
		return false;
	}
	if(file.size != undefined && file.size <= 0) {
		alert("文件内容为空，请重新上传");
		return false;
	}
	if(!checkFileExt(file)) {
		alert("文件格式不支持，请重新上传");
		return false;
	}
	return true;
}
/**
 * 上传附件
 * @param obj	input
 * @param formId	form的id
 * @returns {Boolean}
 */
function uploadFile(obj, formId) {
	if(obj.files != null){
		var file = obj.files[0];
	}else{
		var file = obj.value;
	}
	var form = $("#"+formId);
	if(!checkFile(file,form)){
		form.find(".gd-upload-input").val("");
		return false;
	}
	loading.show({
		loadingText: '上传中',
		// 是否带mask蒙层
		withMask: true
	});
	
	var options = {
			 	url: ctx + "/consult/upload-file",
		        type: "POST",
		        success: function(data) {
		        	data = JSON.parse(data);
		        	if(!data.flag) {
		                alert(data.message);
		                form.find(".gd-upload-input").val("");
		                loading.hide();
		        	} else {
		        		//提交成功
		        		var id = data.result.ID
		        		var filename = data.result.filename;
		        		if(filename){
		        			if(filename.length > 30){
		        				var index = filename.lastIndexOf(".");
		        				filename = filename.substring(0,30) + "..." + filename.substring(index,filename.length);
		        			}
		        		}
		        		var html = '<div class="gd-upload-item" id="file_'+id+'">';
		        		html += '<span class="gd-upload-item-title">'+filename+'</span>';
		        		html += '<a class="gd-upload-item-delete" href="javascript:;" onclick="deleteFile(\''+id+'\',\''+formId+'\')">删除材料</a></div>';
		        		form.find(".fileList").append(html);
		        		//隐藏上传按钮
		        		form.find(".fileUploadDiv").hide();
		        		loading.hide();
		        	}
		        },
		        error: function (data, status, e) {
		            alert("上传文件失败");
		            form.find(".gd-upload-input").val("");
		            loading.hide();
		        },
	}
	form.ajaxSubmit(options);
}

/**
 * 删除附件
 * @param id	附件id
 * @param formId	表单dom的id
 */
function deleteFile(id, formId) {
	loading.show({
		loadingText: '删除中',
		// 是否带mask蒙层
		withMask: true
	});
    $.ajax({
        url: ctx + "/consult/delete-file",
        type: "POST",
        data: {
        	"fileid": id,
        	"type": $("input[name='type']").val(),
        },
        dataType: 'json', //返回值类型 一般设置为json
        success: function(data) {
        	if(data.error) {
                alert(data.errorMessage);
        	} else {
        		$("#"+formId).find("input[type='file']").val("");
        		$("#file_"+id).remove();
        		//显示上传按钮
        		$("#"+formId).find(".fileUploadDiv").show();
        	}
        },
        error: function (data, status, e) {
            alert("删除文件失败");
        },
        complete: function (){
        	loading.hide();
        }
    });
}

/**
 * 获取焦点事件
 * @param dom dom对象
 */
function formFocus(dom) {
	$(dom).parents(".gd-form-item").removeClass("gd-form-item-error");
	$(dom).parents(".gd-form-item-content").children(".gd-form-error").hide();
}
/**
 * 失去焦点事件
 * @param dom dom对象
 */
function formBlur(dom) {
	var error_flag = "";
	if(dom.tagName == "SELECT" && $(dom).find("li.selected").length == 0) {
		error_flag = "null";
	} else if($(dom).val().replace(/\s/ig, '').length == 0) {
		error_flag = "null";
	}else if($(dom).attr("class") != "gd-textarea" && $(dom).val().indexOf(" ") != -1) {
		error_flag = "blank";
	} else if($(dom).val() == $(dom).attr('placeholder')){
		error_flag = "null";
	}
	if(error_flag != "") {
		if(error_flag == "null"){
			$(dom).parents(".gd-form-item").addClass("gd-form-item-error");
			$(dom).parents(".gd-form-item-content").children(".null-error").show();
		}else{
			$(dom).parents(".gd-form-item").addClass("gd-form-item-error");
			$(dom).parents(".gd-form-item-content").children(".blank-error").show();
		}
		
	}
}
/**
 * 校验咨询
 * @param formId
 * @returns {Boolean}
 */
function checkInquire(){
	clearErrortext();
	var form = $("#form");
	var valid = true;
	if(form.find("textarea[name='zxnr']").val().replace(/\s/ig, '').length == 0) {
		showErrortext(form.find("textarea[name='zxnr']"),"此内容不能为空");
		valid = false;
	}
	if(!form.find("select[name='sxbm']").val()) {
		showErrortext(form.find("select[name='sxbm']"),"此内容不能为空");
		valid = false;
	}
	if(!form.find("select[name='zxdx']").val()) {
		showErrortext(form.find("select[name='zxdx']"),"此内容不能为空");
		valid = false;
	}
	if(!form.find("input[name='zxzt']").val()) {
		showErrortext(form.find("input[name='zxzt']"),"此内容不能为空");
		valid = false;
	}
	var yx = $("#zxemail");
	var yxPattern = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
	if(yx.val() && !yxPattern.test(yx.val())){
		showErrortext(yx,"请输入正确的邮箱");
		valid = false;
	}
	
	if(form.find("input[name='checkcode']").length > 0 &&
			!form.find("input[name='checkcode']").val()) {
		showErrortext(form.find("input[name='checkcode']"),"请输入验证码");
		valid = false;
	}
	
	return valid;
}
/**
 * 提交咨询
 * @param formId
 * @returns {Boolean}
 */
function saveInquire(){
	if(!checkInquire()){
		return false;
	}
	//选中的事项
	var itemInfo=$("#itemSelect1").select2("data")[0];
	if(!itemInfo) {
		alert("请选择咨询事项");
		return false;
	}
	$("input[name='itemcode']").val(itemInfo.code);
	$("input[name='itemversion']").val(itemInfo.version);
	$("input[name='itemname']").val(itemInfo.name);
	
	var zxdxInfo = $("#zxdx").select2("data")[0];
	 $("input[name='zzjgmc']").val(zxdxInfo.text);
	 $("input[name='zzjgdm']").val(zxdxInfo.id);
	
    $.ajax({
        url: ctx + "/consult/save-inquire",
        type: "POST",
        data: $("#form").serialize(),
        dataType: 'json', //返回值类型 一般设置为json
        success: function(data) {
        	if(data.error) {
                alert(data.errorMessage);
                refreshCheckcode();
        	} else {
        		location.href = ctx + "/consult/inquire-result?flowid=" + data.result;
        	}
        },
        error: function (data, status, e) {
            alert("提交咨询失败");
        }
    });
	return false;
}

/**
 * 校验纠错
 * @param formId
 * @returns {Boolean}
 */
function checkDebug(){
	clearErrortext();
	var form = $("#form");
	var valid = true;
	if(!form.find("input[name='page_url']").val()) {
		showErrortext(form.find("input[name='page_url']"),"请输入页面地址");
		valid = false;
	}
	if(!form.find("select[name='errorType']").val()) {
		showErrortext(form.find("select[name='errorType']"),"请选择错误类型");
		valid = false;
	}
	if(form.find("textarea[name='content']").val().replace(/\s/ig, '').length == 0) {
		showErrortext(form.find("textarea[name='content']"),"请描述错误内容");
		valid = false;
	}
	/*var phoneInput = form.find("input[name='phone']");
	if(phoneInput.size() > 0 && phoneInput.val().length < 11) {
		showErrortext(phoneInput,"请输入正确的手机号码");
		valid = false;
	}*/
	if(form.find("input[name='checkcode']").length > 0 &&
			!form.find("input[name='checkcode']").val()) {
		showErrortext(form.find("input[name='checkcode']"),"请输入验证码");
		valid = false;
	}
	return valid;
}

/**
 * 提交纠错
 * @param formId
 * @returns {Boolean}
 */
function saveDebug(){
	if(!checkDebug()){
		return false;
	}
	
	if(!checkBlank("form")){
		return false;
	}
	
    $.ajax({
        url: ctx + "/suggest/save-debug",
        type: "POST",
        data: $("#form").serialize(),
        dataType: 'json', //返回值类型 一般设置为json
        success: function(data) {
        	if(data.error) {
                alert(data.errorMessage);
        	} else {
        		location.href = ctx + "/suggest/debug-result";
        	}
        },
        error: function (data, status, e) {
            alert("提交纠错失败");
        }
    });
	return false;
}

/**
 * 校验建议
 * @param formId
 * @returns {Boolean}
 */
function checkAdvice(){
	clearErrortext();
	var form = $("#form");
	var valid = true;
	if(!form.find("input[name='title']").val()) {
		showErrortext(form.find("input[name='title']"),"请输入标题");
		valid = false;
	}
	if(form.find("textarea[name='content']").val().replace(/\s/ig, '').length == 0) {
		showErrortext(form.find("textarea[name='content']"),"请输入建议描述");
		valid = false;
	}
	/*var phoneInput = form.find("input[name='phone']");
	if(phoneInput.size() > 0 && phoneInput.val().length < 11) {
		showErrortext(phoneInput,"请输入正确的手机号码");
		valid = false;
	}*/
	if(form.find("input[name='checkcode']").length > 0 &&
			!form.find("input[name='checkcode']").val()) {
		showErrortext(form.find("input[name='checkcode']"),"请输入验证码");
		valid = false;
	}
	return valid;
}

/**
 * 提交服务建议
 * @param formId
 * @returns {Boolean}
 */
function saveAdvice(){
	if(!checkAdvice()){
		return false;
	}
	
	if(!checkBlank("form")){
		return false;
	}
	
    $.ajax({
        url: ctx + "/suggest/save-advice",
        type: "POST",
        data: $("#form").serialize(),
        dataType: 'json', //返回值类型 一般设置为json
        success: function(data) {
        	if(data.error) {
                alert(data.errorMessage);
        	} else {
        		location.href = ctx + "/suggest/advice-result";
        	}
        },
        error: function (data, status, e) {
            alert("提交服务建议失败");
        }
    });
	return false;
}

/**
 * 校验投诉
 * @param formId
 * @returns {Boolean}
 */
function checkComplain(formId){
	clearErrortext();
	var form = $("#"+formId);
	var valid = true;
	var errorMsg = "";
	var type = "";
	
	if(form.find("[name='subtype']").val()=='sx') {
		errorMsg = "请选择投诉事项";
		type = "sx";
	}
	if(form.find("[name='subtype']").val()=='bm') {
		errorMsg = "请选择投诉部门";
		type = "bm";
	}
	if(!form.find("[name='zzjg']").val()) {
		showErrortext(form.find("[name='zzjg']"), errorMsg);
		valid = false;
	}
	if(!form.find("select[name='tsnrd']").val()) {
		showErrortext(form.find("select[name='tsnrd']"),"请选择投诉内容");
		valid = false;
	}
	if(!form.find("select[name='tsdx']").val()) {
		showErrortext(form.find("select[name='tsdx']"),"请选择投诉对象");
		valid = false;
	}
	if(form.find("textarea[name='tsnr']").val().replace(/\s/ig, '').length == 0) {
		showErrortext(form.find("textarea[name='tsnr']"),"请描述投诉内容");
		valid = false;
	}
	if(!form.find("input[name='tszt']").val()) {
		showErrortext(form.find("[name='tszt']"),"请输入投诉主题");
		valid = false;
	}
	var itemcode = $("#sx_itemcode").val();
	if(type == "sx" && !itemcode){
		showErrortext(form.find("[id='selected-text']"),"请选择投诉事项");
		valid = false;
	}
	var yx = $("#tsemail");
	var yxPattern = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
	if(yx.val() && !yxPattern.test(yx.val())){
		showErrortext(yx,"请输入正确的邮箱");
		valid = false;
	}
	
	if(form.find("input[name='checkcode']").length > 0 &&
			!form.find("input[name='checkcode']").val()) {
		showErrortext(form.find("input[name='checkcode']"),"请输入验证码");
		valid = false;
	}
	
	return valid;
}

/**
 * 校验再次投诉
 * @param formId
 * @returns {Boolean}
 */
function checkComplainAgain(formId){
	clearErrortext();
	var form = $("#"+formId);
	var valid = true;
	var tsnrd = $('#tsnrdname').val();
	
	if(!$("#"+tsnrd).val()) {
		showErrortext($("#"+tsnrd),"请选择投诉内容");
		valid = false;
	}
	
	if(form.find("textarea[name='tsnr']").val().replace(/\s/ig, '').length == 0) {
		showErrortext(form.find("textarea[name='tsnr']"),"请描述投诉内容");
		valid = false;
	}
	
	var yx = $("#tsemail");
	var yxPattern = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
		if(yx.val() && !yxPattern.test(yx.val())){
			showErrortext(yx,"请输入正确的邮箱");
			valid = false;
		}
	return valid;
}
/**
 * 提交投诉
 * @param formId
 * @returns {Boolean}
 */
function saveComplain(formId){
	var form = $("#"+formId);
	if(!checkComplain(formId)){
		return false;
	}
	
	//选中的部门
	if(formId == "form2") {
		var deptInfo=$("#itemSelect2").select2("data")[0];
		if(!deptInfo) {
			alert("请选择投诉部门");
			return false;
		}
		$("#bm_xzqh").val(deptInfo.area);
	}
	
	if($("#sx_xzqhmc").val() == "" || $("#sx_xzqhmc").val() == "省级"){
		var cityText = $("#city option:selected").text();
		if(cityText == "省级"){
			$("#sx_xzqhmc").val("广东省");
		}else{
			$("#sx_xzqhmc").val(cityText);
		}
	}
	
    $.ajax({
        url: ctx + "/consult/save-complain",
        type: "POST",
        data: form.serialize(),
        dataType: 'json', //返回值类型 一般设置为json
        success: function(data) {
        	if(data.error) {
                alert(data.errorMessage);
                refreshCheckcode();
        	} else {
        		location.href = ctx + "/consult/complain-result?flowid=" + data.result;
        	}
        },
        error: function (data, status, e) {
            alert("提交投诉失败");
        }
    });
	return false;
}

$(function(){
	var $tsdx = $('#item-tsdx');
	$tsdx.on('click','input[name=isjg]',function(){
		$('.gd-form-error',$tsdx).hide();
	});
	var $tsnr = $('#item-tsnr')
	$tsnr.on('click',"select[name='tsnrd']",function(){
		$('.gd-form-error',$tsnr).hide()
	})
})

/**
 * 提交投诉
 * @param formId
 * @returns {Boolean}
 */
function saveComplainAgain(){
	if(!checkComplainAgain("form1")){
		return false;
	}
	
    $.ajax({
        url: ctx + "/consult/save-complain-again",
        type: "POST",
        data: $('#form1').serialize(),
        dataType: 'json', //返回值类型 一般设置为json
        success: function(data) {
        	if(data.error) {
                alert(data.errorMessage);
        	} else {
        		location.href = ctx + "/consult/complain-result?flowid=" + data.result;
        	}
        },
        error: function (data, status, e) {
            alert("提交投诉失败");
        }
    });
	return false;
}

/**
 * 显示表单错误信息
 * @param inputDom	输入框
 * @param text	错误信息(已不再使用)
 */
function showErrortext(inputDom, text) {
	var domClass = "gd-form-item";
	var parentClass = "gd-form-item-content";
	var errorClass = "gd-form-item-error";
	var errorText = '<div class="gd-form-error">'+text+'</div>';
	$(inputDom).parents("."+domClass).addClass(errorClass);
	$(inputDom).parents("."+parentClass).find(".null-error").show();
}

/**
 * 清除错误信息
 */
function clearErrortext(){
	$(".gd-form-item-error").removeClass("gd-form-item-error");
	$(".gd-form-error").hide();
}

/**
 * 初始化事项选择器
 * @param dataBodyId	事项列表body的id
 * @param textDivId	展示框id
 * @returns {___anonymous9337_9484}
 */
function initMatterPicker(dataBodyId, textDivId, scrollId) {
	var page = 1;
	var pageSize = 10;
	var totalPage = 1;
	var data = [];
	var dataCount = 0;
	var dataBody = $("#"+dataBodyId);
	var text = $("#"+textDivId);
	var refresh = true;	//控制下拉数据
	var time = 0;
	
	function getData() {
		if(!refresh) {
			return false;
		}
		loading.show({
			loadingText: '数据加载中',
	    	withMask: false
	  	});
		//防止重复拉取
		refresh = false;
		$("#noMatter").hide();
		time = new Date().getTime();
		var time_flag = time;
		$.ajax({
			"url": ctx+"/consult/paged-done-list",
			"data": {
				page: page,
				pageSize: pageSize,
				startDate: $("input[name='startDate']").val()?$("input[name='startDate']").val() + " 00:00:00":null,
				endDate: $("input[name='endDate']").val()?$("input[name='endDate']").val() + " 23:59:59":null,
				deptCode:$("input[name='deptCode']").val(),
				region:$("#area").val()
			},
			"type": "POST",
			"dataType": "json",
		}).done(function(result){
			if(time_flag != time) {
				//查询已刷新，本次返回结果不展示
				return false;
			}
			if(result.error) {
				alert(result.errorMessage);
				setNoData();
				return false;
			}
			if(result.result && result.result.totalCount > 0 ) {
				page = result.result.page;
				totalPage = result.result.pageCount;
			} else {
				if (page == 1) {
					setNoData();
				}
				return;
			}
			var template = '<tr>'+
					'<td><label class="form-radio-wrapper"><input type="radio" name="matter" number="{no}"><span></span></label></td>'+
					'<td><label class="form-radio-wrapper"><div>{matter_name}</div></label></td>'+
					'<td>{date}</td>'+
					'<td>{sn}</td>'+
					'<td>{matter_dept_name}</td>'+
					'</tr>';
			var html = "";
			$(result.result.data).each(function(i, item){
				var sn = item.sn;
				var matter_id = item.matter_id;
				var matter_name = item.matter_name;
				var matter_dept = item.matter_dept;
				var matter_dept_name = item.matter_dept_name;
				var date = item.create_time;
				html += template.replace(/{sn}/g, sn)
								.replace(/{no}/g, dataCount+i)
								.replace(/{matter_id}/g, matter_id)
								.replace(/{matter_name}/g, matter_name)
								.replace(/{date}/g, date)
								.replace(/{matter_dept_name}/g, matter_dept_name);
				data[dataCount+i] = item;
			});
			dataCount+=result.result.data.length;
			$("#"+dataBodyId).append(html);
			page++;
			//判断是否已经最后
			if(page >  result.result.pageCount){
				refresh = false;
			} else {
				refresh = true;
			}
		}).always(function(){
			loading.hide();
		});
	};
	function selectMatter() {
		var input = $("input[name='matter']:checked");
		if(input.length <= 0) {
			alert("请选择事项。");
			return false;
		}
		var item = data[input.attr("number")];
		$("#sx_sblsh").val(item.sn);
		$("#sx_xzqh").val(item.matter_area);
		$("#sx_zzjg").val(item.matter_dept);
		$("#sx_zzjgmc").val(item.matter_dept_name);
		$("#sx_itemcode").val(item.matter_id);
		$("#sx_itemversion").val(item.matter_version);
		$("#sx_itemname").val(item.matter_name);
		$("#sx_ybsxname").val(item.matter_name);
		$("#"+textDivId).html(item.matter_name);
		$("#not-select").hide();
		$("#selected").show();
		$("#cancelMatterPicker").click();
		
		//带出投诉对象
		renderTsdx(item.matter_dept);
		
		clearMatter();
	};
	function clearMatter() {
		$("#"+scrollId).unbind('scroll');
		$("#"+scrollId).scrollTop("0");
		$("#"+dataBodyId).empty();
		refresh = true;
	};
	function setScroll() {
		refresh = true;
		page = 1;
		data=[];
		dataCount=0;
		// 滚动到底部刷新
		var scroll = $("#"+scrollId);
		scroll.unbind('scroll');
		getData();
		scroll.scroll(function() {
			var nDivHight = scroll.height();
		    var nScrollHight = scroll[0].scrollHeight;
		    var nScrollTop = scroll[0].scrollTop;
			if(nScrollTop + nDivHight >= nScrollHight - 10){
				getData();
			}
		});
	};
	function setNoData(){
		var refresh = false;	//控制下拉数据
		$("#noMatter").show();
	}
	return {
		init: function(){
			clearMatter();
			$("input[name='startDate']").val("");
			$("input[name='endDate']").val("");
			setScroll();
		},
		refresh: function() {
			clearMatter();
			setScroll();
		},
		next: function(){getData();},
		clear: function(){clearMatter();},
		select: function(){selectMatter();}
	};
}

/**
 * 提交时检验页面地址、姓名和验证码是否含有空格
 * @param form
 * @returns
 */
function checkBlank(form){
	var flag = true;
	$("#"+form).find("input[type!=hidden]").each(function(){
		$this = $(this);
		if($this.val().indexOf(" ") != -1){
			$this.parents(".gd-form-item").addClass("gd-form-item-error");
			$this.parents(".gd-form-item-content").find(".blank-error").show();
			flag = false;
		}
	})
	return flag;
}

/**
检验文本框输入空格时需提示
*/
function validateBlankw(obj){
	$this = $(obj);
	if($this.value.indexOf(" ") != -1){
		$this.parents(".gd-form-item").addClass("gd-form-item-error");
		$this.parents(".gd-form-item-content").find(".blank-error").show();
	}
}
/**
 * 实现空格不计数
 */
function notCountBlank(obj){
	var $this = $(obj);
    var _val = $this.val();
    var _length = _val.length;
    var nonBlank_length = _val.replace(/\s/ig, '').length;
    var blank_length = _length - nonBlank_length;
    var maxlength = $this.data('max-length');
    $this.attr("maxlength",maxlength+blank_length);
}

/**
 * 校验建议
 * @param formId
 * @returns {Boolean}
 */
function checkQuerySearch(){
	clearErrortext();
	var form = $("#form");
	var valid = true;
	if(!form.find("input[name='sbrmc']").val()) {
		showErrortext(form.find("input[name='sbrmc']"),"请输入申办人名称");
		valid = false;
	}
	if(!form.find("input[name='sblsh']").val()) {
		showErrortext(form.find("input[name='sblsh']"),"请输入申办流水号");
		valid = false;
	}
	if(!form.find("input[name='captcha']").val()) {
		showErrortext(form.find("input[name='captcha']"),"请输入验证码");
		valid = false;
	}
	return valid;
}

/**
 * 渲染投诉对象
 */
function renderTsdx(deptCode){
	$.ajax({
        url: ctx + "/consult/paged-done-dept-list",
        data: {page:1,pageSize:100,deptCode:deptCode},
        dataType: 'json', //返回值类型 一般设置为json
        success: function(result) {
        	if(result.result && !result.error){
        		var data = result.result.data;
        		var template = "<option value=''></option><option value='#value#'>#text#</option>"
        		var html = "";
        		html += template.replace("#text#",data[0].text).replace("#value#",data[0].id);
        		$("#tsdx").html(html);
        		$("#tsdx").val(data[0].id).trigger('change');
        	}
        },
        error: function (data, status, e) {
            alert("搜索投诉对象失败");
        }
    });
}

function initTsdxSelect2(selector, url, nullMsg) {
    $(selector).select2({
      ajax: {
        url: url,
        dataType: 'json',
        delay: 250,
        type: 'POST',
        data: function (params) {
            return {
                page: params.page,
                deptCode: $("input[name='deptCode']").val(),
                region: $("#area").val()
            };
        },
        processResults: function (result, params) {
            params.page = params.page || 1;
            var itemList = [];//当数据对象不是{id:0,text:'ANTS'}这种形式的时候，可以使用类似此方法创建新的数组对象
            var data = null;
            var totalCount = null;
            if(result.result){
            	data = result.result.data;
            	totalCount = result.result.totalCount;
            	itemList = data;
            }
            return {
                results: itemList,
                pagination: {
                    more: (params.page * 10) < totalCount
                }
            };
        }
      },
      minimumResultsForSearch: -1,
      language: {
    	  loadingMore:function(){return "加载中…"},
    	  searching:function(){return "搜索中…"},
    	  noResults:function(){return nullMsg},
    	  errorLoading:function(){return nullMsg}
      }
    });
}

/**
 * 渲染咨询对象
 */
function renderZxdx(region){
	$.ajax({
		url: ctx + "/custom-config/gdbsNav/index",
		data: {regCode:region},
		type: "POST",
		dataType: 'json', //返回值类型 一般设置为json
		success: function(result) {
			if(result.statusCode == '200' && result.data.data){
				var department = result.data.data.department;
				var current = result.data.data.current;
				$("input[name='xzqhmc']").val(current.ORGNAME);
				$("input[name='xzqh']").val(current.ORGAREACODE);
				$("input[name='orgtype']").val(current.ORGTYPE);
				$("input[name='orgupareacode']").val(current.ORGUPAREACODE);
				$("input[name='orgupareaname']").val(current.city);
				var template = "<option value=''></option><option value='#value#'>#text#</option>"
				var html = "";
				$(department).each(function(i,item){
					html += template.replace("#text#",item.ORGNAME).replace("#value#",item.ORGNUMBER);
				});
				$("#zxdx").html(html);
			}
		},
		error: function (data, status, e) {
			alert("搜索咨询对象失败");
		}
	});
}